from datetime import datetime
from typing import List, Optional
from typing import List
from app.utils.request import RequestHandler
## 数据模型
from app.core.crud import CRUDBase
from app.models.origin.api import Api
from app.models.origin.menus import Menu
from app.models.base.user import User,Role
from app.schemas.base.user import RoleCreate, RoleUpdate,UserCreate, UserUpdate

##密码 
from app.utils.user import get_password_hash, verify_password
from app.services.base.user import user_service,role_service
from app.services.base.user import user_service
from app.schemas.base.login import CredentialsSchema
from app.controllers.family.family_system import family_controller
from app.schemas.base.error_code import *
from app.core.exceptions import BusinessError

from app.utils.app_log import logger

## 角色控制器
class RoleController():
    ## 功能
    pass

## 用户角色
role_controller = RoleController()



## 用户控制层
class UserController():


    ## 用户登录 调services。
    async def user_login(self, credentials: CredentialsSchema):
        ## credentials 模型 就是用户名密码
        return await user_service.authenticate_and_login(credentials)
    
    ## 获取用户列表
    async def user_list(self, page, page_size, q):
        try:
            total, user_objs =  await user_service.list(page=page, page_size=page_size, search=q)
            # logger.info(f"获取用户列表成功，用户数量：{total}")
            data = [await obj.to_dict(m2m=True, exclude_fields=["password"]) for obj in user_objs]  
            # 添加家庭信息
            for item in data:
                family_id = item.pop("family_id", None)
                item["family"] = await (await family_controller.get(id=family_id)).to_dict() if family_id else {}
            
            return total,data
        except Exception as e:
            raise BusinessError(RESOURCE_ACCESS_DENIED ,details=f"""获取用户列表出错：{str(e)}""")

    async def get_user_info(self, user_id: int):
        ## 获取用户信息
        try:
            user_obj = await user_service.get(id=user_id)
            user_dict = await user_obj.to_dict(exclude_fields=["password"])
            return user_dict
        except Exception as e:
            raise BusinessError(RESOURCE_NOT_FOUND.format(resource = "用户") ,details=f"""用户不存在：{str(e)}""")
    
        
    async def remove_user(self,user_id: int):
        try:
            ## 删除用户
            await user_service.remove(user_id)
            return True
        except Exception as e:
            raise BusinessError(RESOURCE_DELETE_FAILED.format(resource = "用户"), details=f"删除用户失败 {str(e)}")
    
    async def reset_password(self,user_id: int):
        ## 重置密码
        try:
            await user_service.reset_password(user_id)
            return True
        except Exception as e:
            raise BusinessError(VALIDATION_ERROR , details=f"重置密码错误 {str(e)}")
    
    async def create_user(self, user_in: UserCreate):
        """创建用户"""
        try:
            user = await user_service.get_by_email(user_in.email)
            if user:
                raise BusinessError(RESOURCE_ALREADY_EXISTS.format(resource = "用户"), details="该邮箱的用户已存在")
            # 更改成传role_data
            new_user = await user_service.create_user(obj_in=user_in)
            await user_service.update_roles(new_user, user_in.role_data)
            return True
        except Exception as e:
            raise BusinessError(RESOURCE_CREATE_FAILED.format(resource = "用户"), details=f"创建用户失败 {str(e)}")
    

    ## 以上是好的  。
    ## 以下，因为用户跟角色之间的绑定关系。。需要重新写看 。
    async def update_user_info(self,user_id: int ,obj_in: UserUpdate = None):
        ## 更新用户信息
        try:
            user = await user_service.update(user_id, obj_in)
            await user_service.update_roles(user, obj_in.role_data)
            return True
        except Exception as e:
            raise BusinessError(RESOURCE_UPDATE_FAILED.format(resource = "用户"), details=f"更新用户失败 {str(e)}")
    

    


user_controller = UserController()

